package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IOrderService;
import com.sand.util.DateTool;
import com.sand.util.PageModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(value = "orderService")
public class OrderServiceImp implements IOrderService {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/2/002 14:35
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;
    //根据id查询订单
    @Override
    public HashMap<String, Object> queryOrderById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t2.userId as landId,t1.leaseEffectiveTime as leaseEffectiveTime," +
                "t1.leaseExpirationTime as leaseExpirationTime,t1.totalRentalPrice as totalRentalPrice,t1.status as status," +
                "t1.remark as remark,t3.communityName as communityName,t4.name as userName,t5.phone as userPhone) " +
                "from OrdertableEntity t1 inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t3 on t2.communityId=t3.rid " +
                "inner join UserdetailsEntity t4 on t1.userId=t4.userId " +
                "inner join UserinfoEntity t5 on t4.userId=t5.rid " +
                "where t1.rid=?0", id);
        HashMap<String, Object> map = list.get(0);
        List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(t1.name as name,t2.phone as phone) " +
                "from UserdetailsEntity t1,UserinfoEntity t2 where t1.userId=t2.rid " +
                "and t1.userId=?0", Integer.parseInt(map.get("landId").toString()));
        map.put("name",list1.get(0).get("name"));
        map.put("phone",list1.get(0).get("phone"));

        return map;
    }
    //分页查询订单
    @Override
    public PageModel<HashMap<String, Object>> queryOrderLimit(int limit, int page, int showWi, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<HashMap<String, Object>>();

        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(OrdertableEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("comName")!=null && !"".equals(obj.get("comName"))){
                List list = baseDao.queryObject("select t1.rid from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid where t2.communityName like '%"+obj.get("comName").toString()+"%'");
                dc.add(Restrictions.in("houseId",list));
            }
            if(obj.get("status")!=null && !"".equals(obj.get("status"))){
                List list = baseDao.queryObject("select t1.rid from OrdertableEntity t1 where t1.status=?0",Integer.parseInt(obj.get("status").toString()));
                dc.add(Restrictions.in("rid",list));
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        dc.setProjection(null);
        dc.setProjection(Projections.property("rid"));
        dc.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.leaseEffectiveTime as leaseEffectiveTime,t1.leaseExpirationTime as leaseExpirationTime," +
                "t1.totalRentalPrice as totalRentalPrice,t1.status as status,t3.communityName as communityName) " +
                "from OrdertableEntity t1 inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t3 on t2.communityId=t3.rid " +
                "where t1.rid in (?0)", list);

        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }

    /**
     * 租客订单查询
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryTenantOrderViewLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(OrdertableEntity.class);
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if (obj.get("userId")!=null) {
                List list = baseDao.queryObject("select t1.rid  from OrdertableEntity t1 where t1.userId = ?0 ",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("rid", list));
            }
            /*criteria.add(Restrictions.eq("status",obj.get("status")));*/

        }

        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);

        //rid的集合
        criteria.setProjection(Projections.property("rid"));

        criteria.addOrder(Order.desc("rid"));

        //查询到所有
        List list = baseDao.queryObjectLimit(criteria, page, limit);

        long i=list1.get(0);

        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject("select new Map(" +
                "t1.rid as rid,t1.userId as userId,t1.paymentMethod as paymentMethod,t1.paymentMethod*t1.price as deposit,t6.status as status," +
                "t6.rid as orderId,t1.houseType as houseType,t1.renovationCondition as renovationCondition,t1.towards as towards," +
                "t2.communityName as communityName,t3.housePicture as housePicture," +
                "t2.communityAddress as communityAddress,t5.name as name," +
                "t6.leaseEffectiveTime as leaseEffectiveTime,t6.leaseExpirationTime as leaseExpirationTime,t6.totalRentalPrice as totalRentalPrice) " +
                "from HouseEntity t1 inner join HouseattachmentEntity t3 on t1.rid=t3.houseId " +
                "inner join OrdertableEntity t6 on t6.houseId=t1.rid " +
                "inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                "inner join CityEntity t5 on t2.cityId=t5.rid " +
                "where t3.isHouse=0 and t6.rid in(?0) group by t1.rid", list);


        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);

        return pm;
    }

    /**
     *查询订单记录
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryOrderByUserIdLimit(int limit, int page,String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(OrdertableEntity.class);
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if (obj.get("userId")!=null) {
                List list = baseDao.queryObject("select t1.rid as rid from HouseEntity t1 inner join OrdertableEntity t2 on t1.rid=t2.houseId where t1.userId = ?0 ",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("houseId", list));
            }

        }

        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);

        //rid的集合
        criteria.setProjection(Projections.property("rid"));

        criteria.addOrder(Order.desc("rid"));

        //查询到所有
        List list = baseDao.queryObjectLimit(criteria, page, limit);

        long i=list1.get(0);
        int count= (int) i;
        //查询订单记录
        List<HashMap<String, Object>> list4 = baseDao.queryObject("select new Map(" +
                "t1.rid as rid,t1.userId as userId,t1.paymentMethod as paymentMethod," +
                "t1.houseType as houseType,t1.renovationCondition as renovationCondition,t1.towards as towards," +
                "t2.communityName as communityName,t3.housePicture as housePicture," +
                "t2.communityAddress as communityAddress,t5.name as name," +
                "t6.leaseEffectiveTime as leaseEffectiveTime,t6.leaseExpirationTime as leaseExpirationTime,t6.totalRentalPrice as totalRentalPrice) " +
                "from HouseEntity t1 inner join HouseattachmentEntity t3 on t1.rid=t3.houseId " +
                "inner join OrdertableEntity t6 on t6.houseId=t1.rid " +
                "inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                "inner join CityEntity t5 on t2.cityId=t5.rid " +
                "where t3.isHouse=0 and t6.rid in(?0) group by t1.rid", list);


        pm.setList(list4);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }


    //添加订单
    @Override
    public boolean addOrder(String data) {
        if(data!=null){
            OrdertableEntity order = JSON.parseObject(data, OrdertableEntity.class);
            //查询房产是否已被下订单并确认
            List list = baseDao.queryObject("select t1.rid from OrdertableEntity t1 where t1.houseId=?0 and t1.status=1", order.getHouseId());
            if(list.size()>0 && list!=null){
                return false;
            }
            //添加订单
            boolean bln = baseDao.addObject(order);
            if(bln){
                //将该房源改为已出租
                List<HouserecordEntity> list1 = baseDao.queryObject("from HouserecordEntity t1 where t1.houseId=?0", order.getHouseId());
                HouserecordEntity house = list1.get(0);
                house.setStatus("已出租");
                baseDao.updateObject(house);
                return true;
            }
        }
        return false;
    }
    //修改订单
    @Override
    public boolean updateOrder(String data) {
        if(data!=null){
            OrdertableEntity order = JSON.parseObject(data, OrdertableEntity.class);
            boolean bln = baseDao.updateObject(order);
            if(bln){
                return true;
            }
        }
        return false;
    }
    //确认订单
    @Override
    public boolean updateOrderStatus(int id) {
        List<OrdertableEntity> list = baseDao.queryObject("from OrdertableEntity t1 where t1.rid=?0", id);
        OrdertableEntity order = list.get(0);
        //查询房产是否已被下订单并确认
        List list2 = baseDao.queryObject("select t1.rid from OrdertableEntity t1 where t1.houseId=?0 and t1.status=1", order.getHouseId());
        if(list2.size()>0 && list2!=null){
            return false;
        }
        //确认订单
        order.setStatus(1);
        boolean bln = baseDao.updateObject(order);
        if(bln){
            //删除其他下订单但是未确认的订单
            List list1 = baseDao.queryObject("from OrdertableEntity t1 where t1.status=0 and t1.houseId=?0 and t1.userId!=?1", order.getHouseId(),order.getUserId());
            baseDao.delAllObject(list1);
            //删除预约此房源的预约信息
            List list3 = baseDao.queryObject("from AppointmentformEntity t1 where t1.houseId=?0", order.getHouseId());
            baseDao.delAllObject(list3);

            //生成合同============================================================
            List<HashMap<String,Object>> list4 = baseDao.queryObject("select new Map(" +
                    "t1.leaseEffectiveTime as leaseEffectiveTime,t1.leaseExpirationTime as leaseExpirationTime," +
                    "t2.phone as userPhone,t3.name as userName,t3.idCard as userIdCard,t4.rid as houseId,t4.userId as landId," +
                    "t4.constructionArea as constructionArea,t4.paymentMethod as paymentMethod,t4.price as price," +
                    "t5.communityName as communityName,t5.communityAddress as communityAddress,t6.name as cityName) " +
                    "from OrdertableEntity t1 inner join UserinfoEntity t2 on t1.userId=t2.rid " +
                    "inner join UserdetailsEntity t3 on t2.rid=t3.userId " +
                    "inner join HouseEntity t4 on t1.houseId=t4.rid " +
                    "inner join CommunityEntity t5 on t4.communityId=t5.rid " +
                    "inner join CityEntity t6 on t5.cityId=t6.rid " +
                    "where t1.rid=?0", order.getRid());
            HashMap<String, Object> map = list4.get(0);
            List<HashMap<String,Object>> list5 = baseDao.queryObject("select new Map(" +
                    "t1.phone as landPhone,t2.name as landName,t2.idCard as landIdCard) " +
                    "from UserinfoEntity t1 inner join UserdetailsEntity t2 on t1.rid=t2.userId " +
                    "where t1.rid=?0", Integer.parseInt(map.get("landId").toString()));
            HashMap<String, Object> map1 = list5.get(0);
            //创建时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String begin = map.get("leaseEffectiveTime").toString();
            String end = map.get("leaseExpirationTime").toString();

            try {
                Date d1=sdf.parse(begin);
                Date d2=sdf.parse(end);
                long con=(d2.getTime()-d1.getTime())/(60*60*24*1000)/30;
                String payMethod="免押金";
                switch (Integer.parseInt(map.get("paymentMethod").toString())){
                    case 1:
                        payMethod="押一付一";
                        break;
                    case 2:
                        payMethod="押一付二";
                        break;
                    case 3:
                        payMethod="押一付三";
                        break;
                }
                String date = sdf.format(d1);
                String day=date.substring(date.lastIndexOf("-")+1);
                if("29".equals(day) || "30".equals(day) || "31".equals(day)){
                    day="28";
                }

                String str="出租人（甲方):"+map1.get("landName")+"\t\t承租人（乙方）及单位:"+map.get("userName")+"\n" +
                        "电话:"+map1.get("landPhone")+"\t\t电话:"+map.get("userPhone")+"\n" +
                        "身份证号:"+map1.get("landIdCard")+"\t身份证号:"+map.get("userIdCard")+"\n\n" +
                        "甲、乙、三方根据中华人民共和国有关法律﹑行政法规和苏州市相关地方性法规的规定，在合法、平等、自愿相互信任的基础上签订本合同，承诺共同遵守。\n\n" +
                        "1.甲方将其位于__"+map.get("cityName")+","+map.get("communityName")+","+map.get("communityAddress")+",识别号为"+map.get("houseId")+"__的房屋（以下简称“该房屋”)租给乙方使用，房屋面积为__"+map.get("constructionArea")+"__平方米。\n\n" +
                        "2.该房屋租赁期限共_"+con+"_个月，自_"+sdf.format(map.get("leaseEffectiveTime"))+"_至_"+sdf.format(map.get("leaseExpirationTime"))+"_止。\n\n" +
                        "3.该房屋租金为人民币_"+map.get("price")+"_元整/月（此价格不含相关税费）﹐乙方应同时交纳首期租金_"+Integer.parseInt(map.get("price").toString())*(Integer.parseInt(map.get("paymentMethod").toString())+1)+"_元给甲方。\n\n" +
                        "4.该房屋租金按_"+payMethod+"_支付，支付时间为 每月_"+day+"_号，以甲方实际收到为准。\n\n" +
                        "\n" +
                        "\t\t\t\t\t签订日期：_"+sdf.format(timestamp)+"_\n";
                map.put("str",str);
                System.out.println("=============>>>>"+str);

                ContractEntity contract = new ContractEntity();
                contract.setOrderId(order.getRid());
                contract.setStatus(-1);
                contract.setContractDate(timestamp);
                contract.setContent(str);
                contract.setConfirm("未审核");
                baseDao.addObject(contract);
                return true;
            } catch (ParseException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    //删除订单
    @Override
    public boolean delOrder(int oid) {
        OrdertableEntity ordertable = (OrdertableEntity) baseDao.queryObjectById(OrdertableEntity.class,oid);
        if(baseDao.delObject(ordertable))return true;
        return false;
    }

    /**
     * 房东钱包信息
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> queryWallet(int userId) {

        Map<String, Object> map = new HashMap();
        try {
            //查询用户余额
            List balance = baseDao.queryObject("select u1.balance from UserdetailsEntity u1 where u1.userId = ?0",userId);
            map.put("balance",balance.size()>0?balance.get(0):0);

            //查询用户租龄
            List RentAge = baseDao.queryObject("select u1.createTime from UserinfoEntity u1 where u1.rid = ?0", userId);
            System.out.println(RentAge);
            SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
            Date fromDate = df.parse(RentAge.get(0).toString());
            System.out.println(fromDate);
            //为当前的时间
            Date date=new Date();
            System.out.println(date);
            SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM-dd");//设置当前时间的格式，为年-月-日
            System.out.println(dateFormat.format(date));
            String strData = yearCompare(fromDate, date);
            map.put("strData",strData);

            //查询房东租户积累数量
            List list = baseDao.queryObject("select count (*) from HouseEntity t1 inner join OrdertableEntity t2 on t2.houseId=t1.rid " +
                    "where t2.status =1 and t1.userId =?0", userId);
            map.put("count",list.size()>0?list.get(0):0);

            //房东收入
            List money = baseDao.queryObject("select SUM(t1.amount) from ContractperformEntity t1 " +
                    "inner join ContractEntity t2 on t1.contractId=t2.rid " +
                    "inner join OrdertableEntity t3 on t3.rid=t2.orderId " +
                    "inner join HouseEntity t4 on t4.rid=t3.houseId where t4.userId = ?0", userId);
            map.put("money",money.size()>0?money.get(0)==null?0: money.get(0):0);

            //房东名下房产量
            List houseCount = baseDao.queryObject("select COUNT(t1.rid)  from HouseEntity t1 where t1.userId = ?0", userId);
            map.put("houseCount",houseCount.size()>0?houseCount.get(0):0);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return map;
    }
    /**
     * 计算2个日期相差多少年
     * 列：2011-02-02  ~  2017-03-02 大约相差 6.1 年
     * @param fromDate
     * @param toDate
     * @return
     */
    public static String yearCompare(Date fromDate, Date toDate){
        DayCompare result = dayComparePrecise(fromDate, toDate);
        double month = result.getMonth();
        double year = result.getYear();
        //返回2位小数，并且四舍五入
        DecimalFormat df = new DecimalFormat("######0.0");
        return df.format(year + month / 12);
    }
    /**
     * 计算2个日期之间相差的  相差多少年月日
     * 比如：2011-02-02 到  2017-03-02 相差 6年，1个月，0天
     * @param fromDate
     * @param toDate
     * @return
     */
    public static DayCompare dayComparePrecise(Date fromDate, Date toDate){
        Calendar from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);

        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int fromDay = from.get(Calendar.DAY_OF_MONTH);

        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int toDay = to.get(Calendar.DAY_OF_MONTH);
        int year = toYear  -  fromYear;
        int month = toMonth  - fromMonth;
        int day = toDay  - fromDay;
        return DayCompare.builder().day(day).month(month).year(year).build();
    }


    //=========================lyl==============================
    //获取订单表内房子的id
    @Override
    public List queryHouseIdList(int uid) {
//        String datestr = DateTool.getNowDataTime("yyyy/MM/dd");
        return baseDao.queryObject("select houseId from OrdertableEntity where leaseExpirationTime > ?0 and userId=?1",new Date(),uid);
    }

    //查询订单信息
    @Override
    public List<HashMap<String, Object>> queryOlderList(int uid) {
        //设置最后的返回集合
        List<HashMap<String, Object>> endList = new LinkedList<>();
        //查询订单信息
        List<OrdertableEntity> list_or = baseDao.queryObject("from OrdertableEntity where userId=?0",uid);
        if(list_or!=null&&list_or.size()>0){
            for(int ia=0;ia<list_or.size();ia++){
                HouseEntity house = (HouseEntity) baseDao.queryObjectById(HouseEntity.class,list_or.get(ia).getHouseId());
                if(house!=null){
                    CommunityEntity communityEntity = (CommunityEntity) baseDao.queryObjectById(CommunityEntity.class,house.getCommunityId());
                    List<HouseattachmentEntity> tempList = baseDao.queryObject("from HouseattachmentEntity where houseId=?0",house.getRid());
                    if(tempList!=null&&tempList.size()>0&&communityEntity!=null){
                        Map<String,Object> map = new HashMap<>();
                        map.put("img",tempList.get(0).getHousePicture());
                        map.put("older",list_or.get(ia));
                        map.put("house",house);
                        map.put("address",communityEntity);
                        endList.add((HashMap<String, Object>) map);
                    }
                }
            }
            return endList;
        }
        return null;
    }

}
